package cn.edu.scau.cmi.ema.dao;

import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.dao.DataAccessException;

import org.springframework.stereotype.Repository;

import org.springframework.transaction.annotation.Transactional;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.Session;


import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;


import cn.edu.scau.cmi.ema.util.CmiSqlUtil;

import java.util.Calendar;

@Repository("EventDAO")
@Transactional
public class EventDAOImpl extends AbstractJpaDao<Event> implements EventDAO {

	private final static Set<Class<?>> dataTypes = new HashSet<Class<?>>(Arrays.asList(new Class<?>[] { Event.class }));

	@PersistenceContext(unitName = "ema")
	private EntityManager entityManager;

	public EventDAOImpl() {
		super();
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public Set<Class<?>> getTypes() {
		return dataTypes;
	}

	@Transactional
	public Event findEventById(Integer id) throws DataAccessException {

		return findEventById(id, -1, -1);
	}

	@Transactional
	public Event findEventById(Integer id, int startResult, int maxRows) throws DataAccessException {
		try {
			Query query = createNamedQuery("findEventById", startResult, maxRows, id);
			return (Event) query.getSingleResult();
		} catch (NoResultException nre) {
			return null;
		}
	}

	@Transactional
	public Set<Event> findEventByName(String name) throws DataAccessException {

		return findEventByName(name, -1, -1);
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public Set<Event> findEventByName(String name, int startResult, int maxRows) throws DataAccessException {
		Query query = createNamedQuery("findEventByName", startResult, maxRows, name);
		return new LinkedHashSet<Event>(query.getResultList());
	}

	@Transactional
	public Set<Event> findEventByNameContaining(String name) throws DataAccessException {

		return findEventByNameContaining(name, -1, -1);
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public Set<Event> findEventByNameContaining(String name, int startResult, int maxRows) throws DataAccessException {
		Query query = createNamedQuery("findEventByNameContaining", startResult, maxRows, name);
		return new LinkedHashSet<Event>(query.getResultList());
	}

	@Transactional
	public Set<Event> findEventBySourceTime(Calendar sourceTime) throws DataAccessException {

		return findEventBySourceTime(sourceTime, -1, -1);
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public Set<Event> findEventBySourceTime(Calendar sourceTime, int startResult, int maxRows)
			throws DataAccessException {
		Query query = createNamedQuery("findEventBySourceTime", startResult, maxRows, sourceTime);
		return new LinkedHashSet<Event>(query.getResultList());
	}

	@Transactional
	public Set<Event> findEventByDiscoveryTime(Calendar discoveryTime) throws DataAccessException {

		return findEventByDiscoveryTime(discoveryTime, -1, -1);
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public Set<Event> findEventByDiscoveryTime(Calendar discoveryTime, int startResult, int maxRows)
			throws DataAccessException {
		Query query = createNamedQuery("findEventByDiscoveryTime", startResult, maxRows, discoveryTime);
		return new LinkedHashSet<Event>(query.getResultList());
	}

	@Transactional
	public Set<Event> findEventByAuditTime(Calendar auditTime) throws DataAccessException {

		return findEventByAuditTime(auditTime, -1, -1);
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public Set<Event> findEventByAuditTime(Calendar auditTime, int startResult, int maxRows)
			throws DataAccessException {
		Query query = createNamedQuery("findEventByAuditTime", startResult, maxRows, auditTime);
		return new LinkedHashSet<Event>(query.getResultList());
	}

	@Transactional
	public Set<Event> findEventByCrawlTime(Calendar crawlTime) throws DataAccessException {

		return findEventByCrawlTime(crawlTime, -1, -1);
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public Set<Event> findEventByCrawlTime(Calendar crawlTime, int startResult, int maxRows)
			throws DataAccessException {
		Query query = createNamedQuery("findEventByCrawlTime", startResult, maxRows, crawlTime);
		return new LinkedHashSet<Event>(query.getResultList());
	}

	@Transactional
	public Set<Event> findEventByStatus(Boolean status) throws DataAccessException {

		return findEventByStatus(status, -1, -1);
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public Set<Event> findEventByStatus(Boolean status, int startResult, int maxRows) throws DataAccessException {
		Query query = createNamedQuery("findEventByStatus", startResult, maxRows, status);
		return new LinkedHashSet<Event>(query.getResultList());
	}

	@Transactional
	public Set<Event> findEventByDescription(String description) throws DataAccessException {

		return findEventByDescription(description, -1, -1);
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public Set<Event> findEventByDescription(String description, int startResult, int maxRows)
			throws DataAccessException {
		Query query = createNamedQuery("findEventByDescription", startResult, maxRows, description);
		return new LinkedHashSet<Event>(query.getResultList());
	}

	@Transactional
	public Set<Event> findEventByDescriptionContaining(String description) throws DataAccessException {

		return findEventByDescriptionContaining(description, -1, -1);
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public Set<Event> findEventByDescriptionContaining(String description, int startResult, int maxRows)
			throws DataAccessException {
		Query query = createNamedQuery("findEventByDescriptionContaining", startResult, maxRows, description);
		return new LinkedHashSet<Event>(query.getResultList());
	}

	@Transactional
	public Event findEventByPrimaryKey(Integer id) throws DataAccessException {
		return findEventByPrimaryKey(id, -1, -1);
	}

	@Transactional
	public Event findEventByPrimaryKey(Integer id, int startResult, int maxRows) throws DataAccessException {
		try {
			Query query = createNamedQuery("findEventByPrimaryKey", startResult, maxRows, id);
			return (Event) query.getSingleResult();
		} catch (NoResultException nre) {
			return null;
		}
	}

	@Transactional
	public Set<Event> findEventsByIds(Set<Integer> ids) throws DataAccessException {
		try {
			Query query = createNamedQuery("findEventsByIds", -1, -1, ids);
			return new HashSet(query.getResultList());
		} catch (NoResultException nre) {
			return null;
		}
	}

	@Transactional
	public Set<Event> findAllEvents() throws DataAccessException {

		return findAllEvents(-1, -1);
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public Set<Event> findAllEvents(int startResult, int maxRows) throws DataAccessException {
		Query query = createNamedQuery("findAllEvents", startResult, maxRows);
		return new LinkedHashSet<Event>(query.getResultList());
	}

	@SuppressWarnings("unchecked")
	public Set<Event> findEventsBySourceAddress(Integer addressId, int start, int max) throws DataAccessException {
		Query query = createNamedQuery("findAllEventsBySourceAddress", start, max, addressId);
		return new LinkedHashSet<Event>(query.getResultList());
	}

	@SuppressWarnings("unchecked")
	public Set<Event> findEventsByDiscoveryAddress(Integer addressId, int start, int max) throws DataAccessException {
		Query query = createNamedQuery("findAllEventsByDiscoveryAddress", start, max, addressId);
		return new LinkedHashSet<Event>(query.getResultList());
	}

	@SuppressWarnings("unchecked")
	public Set<Event> findEventsBySubject(Integer subjectId, int start, int max) throws DataAccessException {
		Query query = createNamedQuery("findAllEventsBySubject", start, max, subjectId);
		return new LinkedHashSet<Event>(query.getResultList());
	}

	@SuppressWarnings("unchecked")
	public Set<Event> findEventsByAuditor(Integer userId, int start, int max) throws DataAccessException {
		Query query = createNamedQuery("findAllEventsByAuditor", start, max, userId);
		return new LinkedHashSet<Event>(query.getResultList());
	}

	@SuppressWarnings("unchecked")
	public Set<Event> findEventsByUrl(Integer urlId, int start, int max) throws DataAccessException {
		Query query = createNamedQuery("findAllEventsByUrl", start, max, urlId);
		return new LinkedHashSet<Event>(query.getResultList());
	}

	@SuppressWarnings("unchecked")
	public Set<Event> findEventsByReportor(Integer userId, int start, int max) throws DataAccessException {
		Query query = createNamedQuery("findAllEventsByReportor", start, max, userId);
		return new LinkedHashSet<Event>(query.getResultList());
	}

	@SuppressWarnings("unchecked")
	public Set<Event> findEventsByParent(Integer eventId, int start, int max) throws DataAccessException {
		Query query = createNamedQuery("findAllEventsByParent", start, max, eventId);
		return new LinkedHashSet<Event>(query.getResultList());
	}

	@SuppressWarnings("unchecked")
	public Set<Event> findEventsByFoodbatch(Integer foodbatchId, int start, int max) throws DataAccessException {
		Query query = createNamedQuery("findAllEventsByFoodbatch", start, max, foodbatchId);
		return new LinkedHashSet<Event>(query.getResultList());
	}

	@Override
	public Set<Integer> findEventIdsByParent(int rootEventId) throws DataAccessException {
		Query query = createNamedQuery("findEventIdsByParent", -1, -1, rootEventId);
		return new LinkedHashSet<Integer>(query.getResultList());
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public Set<Event> findEventByCompositeProperities(String sql, int startResult, int maxRows) {
		return new LinkedHashSet<Event>(createQuery(sql, startResult, maxRows).getResultList());
	}

	@Transactional
	public Set<Event> findEventsByDetachedCriteria(CmiPagination page) throws DataAccessException {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Event.class);
		Session session = entityManager.unwrap(Session.class);
		Set<Event> events = new HashSet(detachedCriteria.getExecutableCriteria(session)
				.setFirstResult(page.getSearchBeginCursor()).setMaxResults(page.getPaginationSize()).list());

		return events;
	}

	@Transactional
	public Event findEventByPhysicalPrimaryKey(Integer subjectId, Integer foodbatchId) throws DataAccessException {
		return findEventByPhysicalPrimaryKey(subjectId, foodbatchId, -1, -1);
	}

	@Transactional
	public Event findEventByPhysicalPrimaryKey(Integer subjectId, Integer foodbatchId, int startResult, int maxRows)
			throws DataAccessException {
		try {
			Query query = createNamedQuery("findEventByPhyscialPrimaryKey", startResult, maxRows, subjectId,
					foodbatchId);
			return (Event) query.getSingleResult();
		} catch (NoResultException nre) {
			return null;
		}
	}

	public boolean canBeMerged(Event entity) {
		return true;
	}
}
